const admin = require('../models/admin')
const jwt = require('jsonwebtoken')
const crypto = require('crypto')

let login = async (req, res, next) => {
	let md5 = crypto.createHash('md5')
	let pass = md5.update(req.body.password).digest('hex')
	req.body.password = pass
	if (req.session.captcha) {
		if (req.body.captcha.toUpperCase() !==
		  req.session.captcha.toUpperCase()) {
			res.json({
				code: 500,
				data: '',
				msg: '验证码不正确'
			})
			return false
		}
	}
	await admin.findOne({
		where: { username: req.body.username, password: req.body.password }
	}).then(result => {
		if (result) {
			let content = { username: req.body.username }
			let token = jwt.sign(content, 'jares', {
				expiresIn: 60 * 60 * 1
			})
			res.json({
				code: 0,
				data: token,
				msg: 'success'
			})
		} else {
			res.json({
				code: 500,
				data: '',
				msg: '用户名或者密码错误'
			})
		}
	})
}

module.exports = {
	login
}
